package com.aoyama.collection.arraylist.v1;

import java.util.Arrays;

/**
 * <p>
 *
 * </p>
 *
 * @author qingshan
 * @since 2021/3/31 4:27 下午
 */
public class ArrayList_ implements List_ {

    /**
     * 存储数据
     */
    private Object[] elementData = new Object[10];

    /**
     * 记录当前元素个数
     */
    private int size;

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean add(Object o) {
        if (size == elementData.length) {
            // 扩容
            Object newElementsData = new Object[elementData.length * 2];
            Arrays.copyOf(elementData, elementData.length * 2);
            elementData[size++] = o;
        } else {
            elementData[size++] = o;
        }
        return true;
    }

    @Override
    public boolean addAll(Object[] objects) {
        if (objects.length + size > elementData.length) {
            // 扩容
            elementData = Arrays.copyOf(elementData, elementData.length * 2);
            System.arraycopy(objects, 0, elementData, size, objects.length);
            size += objects.length;
        } else {
            System.arraycopy(objects, 0, elementData, size, objects.length);
            size += objects.length;
        }
        return true;
    }

    @Override
    public boolean contain(Object o) {
        return false;
    }

    /**
     * 迭代器
     * @return
     */
    @Override
    public Iterator_ iterator() {
        return new Itr();
    }

    private class Itr implements Iterator_ {

        private int cursor; // 游标，下一个将要返回的元素的位置

        private int lastRet; // 最后返回的元素的位置

//        private int ExpectedModCount = modCount;

        @Override
        public Object next() {
//            int i = cursor;
            if (cursor >= size) {
                // 已经越界
                System.out.println("已经越界");
            }
            return elementData[cursor++];
        }

        @Override
        public boolean hasNext() {
            // size是父类（ArrayList_数组的大小）
            return cursor != size;
        }

        @Override
        public void remove() {

        }
    }
}
